package com.ruoyi.web.core.config;

/**
 * @author fuqf1@lenovo.com
 * @version 1.0
 * @date 2022/8/1 20:29
 * @since detail
 */
import java.util.Date;
import java.util.Properties;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;




/**
 *  Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)   拦截执行器的方法
 ParameterHandler (getParameterObject, setParameters)	拦截参数的处理
 ResultSetHandler (handleResultSets, handleOutputParameters)	拦截结果集的处理
 StatementHandler (prepare, parameterize, batch, update, query) 拦截Sql语法构建的处理
 * @author Administrator
 *
 */
@Intercepts({@Signature(type = Executor.class,method = "update",
        args = {MappedStatement.class,Object.class})})
@Component
public class HandleTimeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if(sqlCommandType== SqlCommandType.UPDATE) {
            if(args[1] instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) args[1];
                baseEntity.setUpdateTime(new Date());
                SysUser sysUser= (SysUser) SecurityUtils.getSubject().getPrincipal();
                baseEntity.setUpdateBy(sysUser.getLoginName());
            }
        }else if(sqlCommandType==SqlCommandType.INSERT) {
            if(args[1] instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) args[1];
                baseEntity.setCreateTime(new Date());
                SysUser sysUser= (SysUser) SecurityUtils.getSubject().getPrincipal();
                baseEntity.setCreateBy(sysUser.getLoginName());
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
